package com.sx.core.dao.sql

import com.sx.core.model.Table

import java.lang.annotation.Annotation

/**
 * Created by lihao on 2018/12/6.
 */
class SqlProvider {
    String insertSql(Map parameter){
        def clazz=parameter.get("rec");
        def table,columns=[],columns_str,values=[],values_str;
        Map props=clazz.getProperties();
        props.each {entry->
            if(entry.key=="class"){
                Class aClass=entry.value;
                Annotation tabl=aClass.getAnnotation(Table.class);
                table=tabl.value()
            }else{
                if(entry.value){
                    columns.add(entry.key)
                    values.add("#{rec."+entry.key+"}")
                }
            }
        }

        if(!columns.isEmpty()){
            columns_str=columns.join(',')
            values_str=values.join(',')
        }
        def sql="insert into $table ($columns_str) values($values_str)"
        return sql
    }
    String updateSql(Map parameter){
        def clazz=parameter.get("rec");
        def table,columns=[],columns_str,id;
        Map props=clazz.getProperties();
        props.each {entry->
            if(entry.key=="class"){
                Class aClass=entry.value;
                Annotation tabl=aClass.getAnnotation(Table.class);
                table=tabl.value()
                id=tabl.id().toLowerCase()
            }else{
                if(entry.value){
                    columns.add(entry.key+" = #{"+entry.key+"}")
                }
            }
        }

        if(!columns.isEmpty()){
            columns_str=columns.join(',')
        }
        def sql="update $table set $columns_str where $id=#{$id}"
        return sql
    }
    String deleteSql(Map parameter){
        def clazz=parameter.get("rec");
        Annotation tabl=clazz.getAnnotation(Table.class);
        def table=tabl.value()
        def id=tabl.id().toLowerCase()

        def sql="delete from $table where $id=#{id}"
        return sql
    }
    String getSql(Map parameter){
        def clazz=parameter.get("rec");
        Annotation tabl=clazz.getAnnotation(Table.class);
        def table=tabl.value()
        def id=tabl.id().toLowerCase()

        def sql="select * from $table  where $id=#{id}"
        return sql
    }
    String listSql(Map parameter){
        def clazz=parameter.get("rec");
        Annotation tabl=clazz.getAnnotation(Table.class);
        def table=tabl.value()
        def sql="select * from $table "
        return sql
    }





}
